import { useAppStore } from '@/store/app'
import { AjaxRequestConfig } from 'uni-ajax'
import { authApi } from '@/api/server'
const reGetToken = async () => {
  const appStore = useAppStore()
  const { code } = await uni.login()
  const res = await authApi(code)
  const { token: newToken, userId } = res
  appStore.updateToken(newToken)
  appStore.updateUserId(userId)
  return newToken
}
export const injectToken = async (config: AjaxRequestConfig): Promise<AjaxRequestConfig> => {
  const appStore = useAppStore()
  let token = appStore.accessToken
  const tokenTime = appStore.tokenTime
  const { scene } = appStore.launchOptionsInfo
  // 如果token不存在，则登录并保存token,在朋友圈单页模式中打开，则不用获取token，获取不到
  // 如果token存在，则判断token是否过期
  if (config.url === '/user/authentication') {
    // 直接调
    token && (config.header = { ...config.header, Authorization: `Bearer ${token}` })
    return Promise.resolve(config)
  } else if (!token && scene !== 1154) {
    // 第一次登录或缓存清除
    token = await reGetToken()
  } else if (token && tokenTime > 0) {
    // token过期
    const differenceValue = Date.now() - tokenTime
    if (differenceValue > 48 * 60 * 60 * 1000 - 10000) {
      // 重新获取
      token = await reGetToken()
    }
  }
  token && (config.header = { ...config.header, Authorization: `Bearer ${token}` })
  return Promise.resolve(config)
}
